

import { ref, onMounted } from 'vue';
import { FormSchema } from '/@/components/Table';
import * as diyEnum from "/@/enums/diyFormEnum";
import { RenderCallbackParams, ComponentType, ColEx } from "/@/components/Form"

interface CustomFormSchema {
  field: string
  label: string
  required?: boolean
  component: ComponentType
  helpMessage?: string
  placeholder?: string
  fieldAfter?: string
  dictType?: string
  defaultValue?: any
  colProps?: Partial<ColEx>
  componentProps?: Object
}

interface Options {
  fixedFormSchema: FormSchema[]
  colProps: Partial<ColEx>
  /**
   * 自定义字段名比如 customField: { name: 'test' } 这里就填写 customField
   */
  customFieldName: String
  dynamicDisabled?: boolean | ((renderCallbackParams: RenderCallbackParams) => boolean)
}
export function useDiyFormField(options: Options) {
  const customFieldNamePre = options.customFieldName || 'customField' as string;
  /**
   * 获取表格元素
   */
  const getFormSchemas = async (customFormSchema: CustomFormSchema[]): Promise<FormSchema[]> => {
    const formSchemas = [ ...(options.fixedFormSchema || []) ]
  
    // extra
    customFormSchema.forEach((item) => {
      const componentProps = item.componentProps || {} as any
      componentProps.placeholder = item.placeholder
      componentProps.dictType = item.dictType

      console.log('item', item)
      let newSchema : FormSchema = {
        field: `${customFieldNamePre}_${item.field}`,
        label: item.label,
        show: true,
        required: item.required,
        componentProps: componentProps,
        helpMessage: item.helpMessage,
        defaultValue: item.defaultValue,
        dynamicDisabled: options.dynamicDisabled,
        colProps: item.colProps || options.colProps || {},
        component: item.component,
      }

      if (item.component == 'ApiSelect') {
        const componentProps : any = {
          ...newSchema.componentProps,
          showSearch: true,
          api: async () => {
            // const data = fieldValueList
            // return data
            return null
          },
          labelField: "attrName",
          valueField: "attrValue",
          optionFilterProp: "label",
        }
        newSchema.componentProps = componentProps
      }
      console.log('插入字段', item.field)
      if (item.fieldAfter) {
        // 调整位置
        const keyIndex = formSchemas.findIndex(obj => obj.field === item.fieldAfter);
        if (keyIndex !== -1) {
          // 将新对象插入到 对象的后面
          formSchemas.splice(keyIndex + 1, 0, newSchema);
          console.log(`调整 ${item.field} 到 ${item.fieldAfter} 后边成功, index: ` + keyIndex)
        } else {
          console.warn(`未找到 field = '${item.fieldAfter}' 的字段`);
          formSchemas.push(newSchema)
        }
      } else {
        formSchemas.push(newSchema)
      }
    })
    return formSchemas
  }

  const extractCustomFields = (customFields = {}) => {
    const data = {};
    for (const key in customFields) {
      data[`${customFieldNamePre}_${key}`] = customFields[key];
    }
    console.log('newFormValue', data)
    return data;
  }

  /**
   * 获取表格数据
   */
  const getSubmitFormValue = async (data) => {
    const obj = data || {}
    // 创建一个 customFields 对象，用于存放 custom@ 字段
    const customFields = {};

    // 遍历原对象的字段
    for (const key in obj) {
      if (key.startsWith(customFieldNamePre + '_')) {
        // 去掉前缀，放入 customFields
        const newKey = key.replace(customFieldNamePre + '_', '');
        customFields[newKey] = obj[key];
        // 针对多选优化
        if (customFields[newKey] && customFields[newKey].includes(',')) {
          customFields[newKey] = customFields[newKey].split(',').map(item => item.trim());
        }
        // 删除原对象中的该字段
        delete obj[key];
      }
    }

    // 将 customFields 对象添加到原对象中
    obj[`${customFieldNamePre}`] = customFields;
    console.log('customFields', customFields)
    return obj
  }


  return {
    extractCustomFields,
    getSubmitFormValue,
    getFormSchemas
  }
}
